/**
 * 通用工具类
 * 功能：身份证验证，字符串验证，
 */
(function(){ 
    var _curTime = 0;
    
	function _isPhoneNumber(phoneNumber){
        var re=new RegExp(/^1\d{10}$/);
        var retu=phoneNumber.match(re);
        if(retu){
            return true;
        }else{
            return false;
        }
    }

    function _isValidateIdCard(idCard){
        //15位和18位身份证号码的正则表达式
        var regIdCard=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        //如果通过该验证，说明身份证格式正确，但准确性还需计算
        if(regIdCard.exec(idCard)){
           // return true;
            if(idCard.length==18){
                var idCardWi=new Array( 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ); //将前17位加权因子保存在数组里
                var idCardY=new Array( 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
                var idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
                for(var i=0;i<17;i++){
                    idCardWiSum+=idCard.substring(i,i+1)*idCardWi[i];
                }

                var idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
                var idCardLast=idCard.substring(17);//得到最后一位身份证号码

                //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
                if(idCardMod==2){
                    if(idCardLast=="X"||idCardLast=="x"){
                        return true;
                    }else{
                        ComponentsUtils.showTips("身份证号码错误！");
                        return false;
                    }
                }else{
                    //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                    if(idCardLast==idCardY[idCardMod]){
                        return true;
                    }else{
                        ComponentsUtils.showTips("身份证号码错误！");
                        return false;
                    }
                }
            } 
        }else{
            ComponentsUtils.showTips("身份证格式不正确!");
            return false;
        }
    }

    function _isPassWord(password){
        var patrn=/^(\w){6,18}$/; 
        if (!patrn.exec(password)) return false 
        return true 
    }

    function _isVerify(verify){
        var re=new RegExp(/^\d{6}\b/);
       if (!re.exec(verify)) return false 
        return true 
    }

    function _isChineseChar(name){
        var re = /^[\u4e00-\u9fa5]+$/;
        if (!re.exec(name)) return false 
            return true   
    }

    //匹配数字、大小写字母、下划线、中线和点
    function _isPasswd1(s){ 
        var patrn=/[^a-z|A-Z|0-9|\-|_|\.]/g; 
        if (!patrn.exec(s)) return false 
        return true;
    }

    function _isNiceName(s){
        var patrn=/^[0-9a-zA-Z\u4e00-\u9fa5_]{3,16}$/; 
        if (!patrn.exec(s)) return false 
        return true;
    }

    function _isNumAndAbc(s){
        var patrn=/^[0-9a-zA-Z]+$/g; 
        if (!patrn.exec(s)) return false 
        return true;
    }
        
    //含0
    function _isInt(num){
        var re = /^[0-9]{1,20}$/; 
       
        if (!re.exec(num)) return false 
            return true 
    }

    //不含0
    function _isInt1(num){
        var re = /^\+?[1-9][0-9]*$/;
        if (!re.exec(num)) return false 
            return true 
    }

    function _isFolatMoney(num){
        var re = /^[0-9]+([.]{1}[0-9]{1,2})?$/;
        if (!re.exec(num)) return false 
            return true 
    }

    //只能是数字和.
    function _isNumAndDot(num){
        var re =  /^([1-9][0-9]*)+(.[0-9]{1,2})?$/;
        if (!re.exec(num)) return false 
            return true 
    }

    //手机号-密码-验证码-新密码-是否提示
    function _checkInput(edaccount,edPassword,enVerify,edPasswordNew,bshow){ 
      //  cc.log("检查输入");
        var bret = true;
        var tip = "";
        if(edaccount !==null && edaccount === "")
        {
           tip = "请输入账号";
           bret = false;
        }
        else if(edaccount !==null && !this.isPhoneNumber(edaccount))
        {
            tip = "账号格式不对，请重新输入";
            bret = false;
        }
        else if(edPassword !==null && edPassword === "" || edPasswordNew !==null && edPasswordNew === "")
        {
            tip = "请输入密码";
            bret = false;
        }
        else if(edPassword !==null && !this.isPassWord(edPassword) || edPasswordNew != null && !this.isPassWord(edPasswordNew))
        {
            tip = "密码格式不对，请重新输入";
            bret = false;
        }
        else if(enVerify !==null && enVerify === "")
        {
            tip = "请输入验证码";
            bret = false;
        }
        else if(enVerify !==null && !this.isVerify(enVerify))
        {
           // tip = "验证码格式不对，请重新输入";
           // bret = false;
        }
        else if(edPassword != null && edPasswordNew != null && edPassword !== edPasswordNew)
        {
            tip = "两次密码输入不一致,请重新输入";
            bret = false;
        }

        if(bshow)
            ComponentsUtils.showTips(tip);

        return bret;
    }

    function _getEquipment(){
        if (cc.sys.isNative&&cc.sys.os==cc.sys.OS_IOS)
        {
            return "IOS";
        }
        else if(cc.sys.isNative&&cc.sys.os==cc.sys.OS_ANDROID)
        {
            return "ANDROID";
        }
        else if(!cc.sys.isNative)
        {
            return "WEB";
        }
        else
        {
            return "OTHER";
        }
    }

    function _getSourceType(){
        if (cc.sys.isNative&&cc.sys.os==cc.sys.OS_IOS)
        {
            return 2;
        }
        else if(cc.sys.isNative&&cc.sys.os==cc.sys.OS_ANDROID)
        {
            return 1;
        }
        else if(cc.sys.isNative&&cc.sys.os==cc.sys.IPAD)
        {
            return 3;
        }
        else if(!cc.sys.isNative)
        {
            return 0;
        }
        else
        {
            return 0;
        }
    }
	
	function _getRandomArrayWithArray(array, amount){
        var _arrray = [];
        for(var i = 0; i<array.length; i++){
            _arrray.push(array[i]);
        }
        var finalArray = [];
        for(var i = 0; i<amount; i++){
            var randomIndex = _getRandomNum(0, _arrray.length-1);
            //cc.log("机选ID:"+randomIndex.toString());
            finalArray.push(_arrray[randomIndex]);
            _arrray.splice(randomIndex, 1);
        }
        return finalArray;
    }
	
	function _getRandomNum(Min,Max){   
        //Math.random()*(n-m)+m
        var Range = Max - Min;   
        var Rand = Math.random(); 
        //cc.log("rand:"+Rand);  
        //return(Min + Math.round(Rand * Range));   
        return Math.round(Min+Rand * Range);
    } 
	
	function _culculateAmoutByNumArray(numArray, numberPerCompose){
        var _numArray = numArray;    
        //先判断numarray当中是否有重复的数字
        _numArray.sort();  //用sort()方法对数组进行一个简单的排序
        
        for(var i=0;i<_numArray.length;){
            if(_numArray[i]==_numArray[i+1]){
                _numArray.splice(i,1);  //万能的splice()方法
            }else{
                i++;
            }
        }
        var arrayLength = _numArray.length;
        var m = 1;
        for(var i = arrayLength; i> arrayLength-numberPerCompose; i--){
            m = m*i;
        }
        var n = 1;
        for(var i = numberPerCompose; i> 0; i--){
            n = n*i;
        }
        var amout = m/n;
   
        return amout;
    }
    
    //数字千位分隔符
    function _numSplice1(str){
        var str = str.toString();
        var re = /(?=(?!\b)(\d{3})+$)/g; 
        return str.replace(re, ','); 
    }
    
    function _appendStringArrayBySplit(strArray, split){
        var str = "";
        for(var i = 0; i<strArray.length; i++){
            if(str == ""){
                str = str+strArray[i];
            }else{
                str = str+","+strArray[i];
            }
        }
        return str;
    }

    function _getCurServerTime(){     
        return _curTime;
    }

    function _correctionTime(){
        var data = {
            Token:User.getLoginToken(),
        }
        var ret = CL.HTTP.sendSynchroRequest(DEFINE.HTTP_MESSAGE.GETSERVERTIME, data,"POST");   
        if(ret != null)
        {
            if(ret.Code === 0){
                 return ret.ServerTime;
            }
        }
        return null;
    }

    function _removeByValue(arr, val) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i] == val) {
                arr.splice(i, 1);
                return true;
            }
        }
        return false;
    }

    function _retmoveByType(arr, val,type){
        for(var i=0; i<arr.length; i++) {
            var value = arr[i][type];
            if(value == val) {
                arr.splice(i, 1);
                return true;
            }
        }
        return false;
    }

    function _sortNum(arr){
        function sequence(a,b){
            if (a>b) {
                return 1;
            }else if(a<b){
                return -1
            }else{
                return 0;
            }
        }
        arr.sort(sequence);
    }
    
    function _sortByKey(attr,key,rev){
        if(attr == null)
            return;
        //第二个参数没有传递 默认升序排列
        if(rev ==  "undefined"){
            rev = 1;
        }else{
            rev = (rev) ? 1 : -1;
        }
        function sequence(a,b){
            a = a[key];
            b = b[key];
            if(a < b){
                return rev * -1;
            }
            if(a > b){
                return rev * 1;
            }
            return 0;
        }

        attr.sort(sequence);
    }

    function _getDateForStringDate(str){
        var strTemp = str.toString();
        var year = str[0]+str[1]+str[2]+str[3];
        var month = str[4]+str[5];
        var day = str[6]+str[7];
        var hour = str[8]+str[9];
        var minute = str[10]+str[11];
        var second = str[12]+str[13];
        var timeStr = year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;
        // cc.log("timeStr test2:"+timeStr);
        var date = new Date(timeStr);
        return date;
    }

    function _getNowFormatDate(){
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var min = date.getMinutes();
        var second = date.getSeconds()
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }

        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }

        if (min >= 0 && min <= 9) {
            min = "0" + min;
        }

        if (second >= 0 && second <= 9) {
            second = "0" + second;
        }

        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + hours + seperator2 + min
                + seperator2 + second;
        return currentdate;
    }

    function _formateServiceDateStrToDate(str){
        var strTemp = str.toString();
        var year = str[0]+str[1]+str[2]+str[3];
        var month = str[4]+str[5];
        var day = str[6]+str[7];
        var hour = str[8]+str[9];
        var minute = str[10]+str[11];
        var second = str[12]+str[13];
        var timeStr = year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;
        var date = new Date(timeStr);
        return date;
    }

    function _byTimeGetStr(str,spce1,spce2){
        var strTemp = str.toString();
        var year = str[0]+str[1]+str[2]+str[3];
        var month = str[4]+str[5];
        var day = str[6]+str[7];
        var hour = str[8]+str[9];
        var minute = str[10]+str[11];
        var second = str[12]+str[13];
        var timeStr = year+spce1+month+spce1+day+" "+hour+spce2+minute+spce2+second;
        return timeStr;
    }

    //字符串月日时分
    function _getYMDHMbyTime(str,spce1,spce2){
        var unixTime = new Date(str* 1000);
        var y = unixTime.getFullYear();  
        var m = ((unixTime.getMonth() + 1) > 10 ? (unixTime.getMonth() + 1) : '0' + (unixTime.getMonth() + 1));
        var d = (unixTime.getDate() > 10 ? unixTime.getDate() : '0' + unixTime.getDate());
        var h = unixTime.getHours();  
        //var mm = unixTime.getMinutes();//
        var mm = (unixTime.getMinutes().toString().length == 1 ? '0' + unixTime.getMinutes() : unixTime.getMinutes());  
        var timeStr = y+spce1+m+spce1+d+" "+h+spce2+mm;
        return timeStr;
    }

    //字符串年月日
    function _getYMDbyTime(str,spce){
        var strTemp = str.toString();
        var year = str[0]+str[1]+str[2]+str[3];
        var month = str[4]+str[5];
        var day = str[6]+str[7];
        var timeStr = year+spce+month+spce+day;
        return timeStr;
    }

    //查找数组中某个值
    function _findValueByArry(arr, value){  
        var i = arr.length;  
        while (i--) {  
            if (arr[i] === value) {  
                return true;  
            }  
        }  
        return false;  
    }  

    function _findObjByArry(arr, type, value){
        var i = arr.length;  
        while (i--) {  
            if (arr[i][type] === value) {  
                return arr[i];
            }  
        }  
        return null;  
    }

    function _preNodeComplex(ndOpenPanle,openItemHeight,spacing,reaCount,openItemArr,buffer,_openData,_color,scriptName,nType){
        var offset =(openItemHeight+spacing)*reaCount;
        var isDown =ndOpenPanle.y <Utils.lastPositionY;
        for(var i=0;i<openItemArr.length;++i){
            var itemPos =Utils.getItemPosition(openItemArr[i],ndOpenPanle);
            if(isDown){
                if(itemPos.y< -buffer && openItemArr[i].y+offset<0 ){
                    openItemArr[i].setPositionY(openItemArr[i].y+offset);
                    var itemThis =openItemArr[i].getComponent(scriptName);
                    var childItemId =itemThis._itemId -openItemArr.length;
                    itemThis.onItemIndex(childItemId);
                    switch(scriptName){
                        case 'double_open_item':
                            var data = {
                                Isuse:_openData[childItemId].i,
                                redNums:_openData[childItemId].rn,
                                blueNums:_openData[childItemId].bn,
                                color:_color[childItemId%2]
                            }; 
                        break;
                        case 'super_open_item':
                            var data = {
                                Isuse:_openData[childItemId].i,
                                frontNums:_openData[childItemId].rn,
                                afterNums:_openData[childItemId].bn,
                                color:_color[childItemId%2]
                            }; 
                        break;
                        case '115_opencontent_item':
                            if(!nType || nType ==1 || nType ==3){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    type:nType
                                };
                            }else if(nType ==3){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].x[0],
                                    span:_openData[childItemId].x[1],
                                    repeat:_openData[childItemId].x[2],
                                    color:_color[childItemId%2],
                                    type:0
                                }    
                            }else if(nType ==2){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    color:_color[childItemId%2],
                                    type:2
                                };
                            }else if(nType ==5){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    color:_color[childItemId%2],
                                    type:3
                                };
                            }
                        break;
                        case 'trend_opencontent_item':    //快三
                            var data = {
                                Isuse:_openData[childItemId].i,
                                num1:_openData[childItemId].n,
                                num2:_openData[childItemId].s,
                                num3:_openData[childItemId].dx,
                                num4:_openData[childItemId].ds,
                                color:_color[childItemId%2]
                            };        
                        break;
                        case 'k3_opencontent_item':
                        var data = {
                            Isuse:_openData[childItemId].i,
                            openNums:_openData[childItemId].n,
                            form:_openData[childItemId].x,
                            color:_color[childItemId%2]
                        };
                        break;
                        case 'trend_issue_item':
                        var data = {
                            Isuse:_openData[childItemId].i.substring(_openData[childItemId].i.length-3,_openData[childItemId].i.length) + "期",
                            color:_color[childItemId%2]
                        };
                        break;
                        case 'trend_content_item':
                        if(nType ==1){
                            var data = {
                                type:1,
                                rt:_openData[childItemId].rt,
                                color:_color[childItemId%2],
                                numColor:null,
                                isSpecial:0,
                            }
                        }else if(nType ==2){
                            // var data = {
                            //     type:1,
                            //     rt:rnamsList[i],
                            //     color:color[(i+_openData.length)%2],
                            //     numColor:colorStr[i],
                            //     isSpecial:1,
                            // }
                        }else if(nType ==3){
                            var data = {
                                type:2,
                                rt:_openData[childItemId].bt,
                                color:_color[childItemId%2],
                                numColor:null,
                                isSpecial:0,
                            }
                        }
                        break;
                        case '115_form_item':
                        var data = {
                            Isuse:_openData[childItemId].i,
                            nums:_openData[childItemId].x,
                            color:_color[childItemId%2]
                        }
                        break;
                    }
                    itemThis.updateData(data);
                
                }
            }else{
                if(itemPos.y> buffer && openItemArr[i].y-offset >-ndOpenPanle.height){
                    openItemArr[i].setPositionY(openItemArr[i].y-offset);
                    var itemThis =openItemArr[i].getComponent(scriptName);
                    var childItemId =itemThis._itemId +openItemArr.length;
                    itemThis.onItemIndex(childItemId);
                    switch(scriptName){
                        case 'double_open_item':
                            var data = {
                                Isuse:_openData[childItemId].i,
                                redNums:_openData[childItemId].rn,
                                blueNums:_openData[childItemId].bn,
                                color:_color[childItemId%2]
                            }; 
                        break;
                        case 'super_open_item':
                            var data = {
                                Isuse:_openData[childItemId].i,
                                frontNums:_openData[childItemId].rn,
                                afterNums:_openData[childItemId].bn,
                                color:_color[childItemId%2]
                            }; 
                        break;
                        case '115_opencontent_item':
                            if(!nType || nType ==1 || nType ==3){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    type:nType
                                };
                            }else if(nType ==4){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].x[0],
                                    span:_openData[childItemId].x[1],
                                    repeat:_openData[childItemId].x[2],
                                    color:_color[childItemId%2],
                                    type:0
                                }
                            }else if(nType ==2){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    color:_color[childItemId%2],
                                    type:2
                                }; 
                            }else if(nType ==5){
                                var data = {
                                    Isuse:_openData[childItemId].i,
                                    openNums:_openData[childItemId].n,
                                    sum:_openData[childItemId].s,
                                    span:_openData[childItemId].sp,
                                    repeat:_openData[childItemId].d,
                                    color:_color[childItemId%2],
                                    type:3
                                };
                            }
                        break;
                        case 'trend_opencontent_item':    //快三
                            var data = {
                                Isuse:_openData[childItemId].i,
                                num1:_openData[childItemId].n,
                                num2:_openData[childItemId].s,
                                num3:_openData[childItemId].dx,
                                num4:_openData[childItemId].ds,
                                color:_color[childItemId%2]
                            };        
                        break;
                        case 'k3_opencontent_item':
                        var data = {
                            Isuse:_openData[childItemId].i,
                            openNums:_openData[childItemId].n,
                            form:_openData[childItemId].x,
                            color:_color[childItemId%2]
                        }; 
                        break;
                        case 'trend_issue_item':
                        var data = {
                            Isuse:_openData[childItemId].i.substring(_openData[childItemId].i.length-3,_openData[childItemId].i.length) + "期",
                            color:_color[childItemId%2]
                        };
                        break;
                        case 'trend_content_item':
                        if(nType ==1){
                            var data = {
                                type:1,
                                rt:_openData[childItemId].rt,
                                color:_color[childItemId%2],
                                numColor:null,
                                isSpecial:0,
                            }
                        }else if(nType ==2){
                            // var data = {
                            //     type:1,
                            //     rt:rnamsList[i],
                            //     color:color[(i+_openData.length)%2],
                            //     numColor:colorStr[i],
                            //     isSpecial:1,
                            // }
                        }else if(nType ==3){
                            var data = {
                                type:2,
                                rt:_openData[childItemId].bt,
                                color:_color[childItemId%2],
                                numColor:null,
                                isSpecial:0,
                            }
                        }
                        break;
                        case '115_form_item':
                        var data = {
                            Isuse:_openData[childItemId].i,
                            nums:_openData[childItemId].x,
                            color:_color[childItemId%2]
                        }
                        break;
                    }
                    itemThis.updateData(data);
                    
                }    
            }
        }
        Utils.lastPositionY =ndOpenPanle.y;
    }

    function _getItemPosition(item,ndOpenPanle){
        var worldPos =item.convertToWorldSpaceAR(cc.p(0,0));
        var itemPos =ndOpenPanle.parent.parent.convertToNodeSpaceAR(worldPos);
        return itemPos;
    }

    var _Utils = {
		//输入验证
		isPhoneNumber:_isPhoneNumber,
		isPassWord:_isPassWord,
		isVerify:_isVerify,
        isInt:_isInt,
        isInt1:_isInt1,
        isNiceName:_isNiceName,
        isPasswd1:_isPasswd1,
        isValidateIdCard:_isValidateIdCard,
        isChineseChar:_isChineseChar,
        isNumAndAbc:_isNumAndAbc,
        isNumAndDot:_isNumAndDot,
        isFolatMoney:_isFolatMoney,
		checkInput:_checkInput,
		
		getEquipment:_getEquipment,//获取当前运行平台
        getSourceType:_getSourceType,//当前平台类型
		
		getRandomArrayWithArray:_getRandomArrayWithArray,
		getRandomNum:_getRandomNum,
		culculateAmoutByNumArray:_culculateAmoutByNumArray,

        appendStringArrayBySplit:_appendStringArrayBySplit,
        correctionTime:_correctionTime,//校正当前时间
        getCurServerTime:_getCurServerTime,
        removeByValue:_removeByValue,//删除指定数组元素
        retmoveByType:_retmoveByType,//删除指定数组元素来至于类型
        sortNum:_sortNum,//元素排序
        sortByKey:_sortByKey,//选择升序/降序

        formateServiceDateStrToDate:_formateServiceDateStrToDate,//解析时间
        getYMDbyTime:_getYMDbyTime,
        getYMDHMbyTime:_getYMDHMbyTime,
        byTimeGetStr:_byTimeGetStr,
        getDateForStringDate:_getDateForStringDate,
        getNowFormatDate:_getNowFormatDate,

        findValueByArry:_findValueByArry,//查找数组中某个值
        findObjByArry:_findObjByArry,//查找数组对象中是否存在某个值
        preNodeComplex: _preNodeComplex,//预制节点复用
        getItemPosition: _getItemPosition,
        lastPositionY: 0,
        numSplice1:_numSplice1//字符串千位分隔符 123454-》123,454
    };
    
    window.Utils = _Utils;
} 
)();
